package network.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

public class ChatThread extends Thread {
	
	private static Vector threads = new Vector();
	
	private Socket sock;
	private BufferedReader reader;
	private BufferedWriter writer;
	
	// 대화명
	private String nickName;
	
	public ChatThread(Socket sock) throws IOException {
		this.sock = sock;
		
		writer = new BufferedWriter(
				new OutputStreamWriter(sock.getOutputStream()));
		
		reader = new BufferedReader(
				new InputStreamReader(sock.getInputStream()));
	}
	
	public void send(String message) throws IOException {
		// sock을 통해 메시지를 보내는 일
		writer.write(message + "\n");
		writer.flush();
	}
	
	public String read() throws IOException {
		return reader.readLine();
	}
	
	@Override
	public void run() {
		// Vector에 자신(ChatThread 객체)을 등록
		synchronized (threads) {
			threads.add(this);
		}
		
		// nickName 초기값 설정
		nickName = sock.getInetAddress().toString();
		
		try {
			String dataFromClient = null;
			while ((dataFromClient = this.read()) != null) {
//				dataFromClient = new String(dataFromClient.getBytes("MS949"), "UTF-8");
				System.out.println(sock.getInetAddress() + ": "
						+ dataFromClient);
				
				if (dataFromClient.startsWith("/nick ")) {
					// 대화명 변경 작업
					String[] sp = dataFromClient.split(" ");
					if (sp.length > 1) {
						// 대화명 변경
						nickName = sp[1];
						send("대화명이 '" + nickName + "'으로 변경되었습니다.");
					}
				} else {
					// 일반 대화 처리 작업
					synchronized (threads) {
						Iterator iter = threads.iterator();
						while (iter.hasNext()) {
							ChatThread t = (ChatThread) iter.next();
							t.send(nickName + ": "
									+ dataFromClient);
						}
					}
				}
			}
		} catch (IOException e) {
		} finally {
			synchronized (threads) {
				threads.remove(this);
			}
			try {
				sock.close();
			} catch (IOException e) {}
			System.out.println("접속이 종료되었습니다. "
					+ sock.getInetAddress());
		}
	}
	
}
